package com.easy.intercepter;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.easy.entity.Detail;
import com.easy.entity.Sysstate;
import com.easy.entity.User;
import com.easy.mapper.DetailMapper;
import com.easy.mapper.SysstateMapper;

public class SysIntercepter implements HandlerInterceptor {
	
	@Resource
	private SysstateMapper sysMapper;
	@Resource
	private DetailMapper detailMapper;


	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		Sysstate selectByPrimaryKey = sysMapper.selectByPrimaryKey(1);
		if(selectByPrimaryKey.getWorking().equals("1")) {
			return true;
		}else {
			HttpSession session = request.getSession();
			User user = (User)session.getAttribute("userinfo");
			if(user.getUsername().equals("liaoxiang")) {
				return true;
			}
			List<Detail> detaiListByUserId = detailMapper.getDetaiListByUserId(user.getId());
			for (int i = 0; i < detaiListByUserId.size(); i++) {
				if(detaiListByUserId.get(i).getCheckflag()==0) {
					return true;
				}
			}
			response.sendRedirect(request.getContextPath()+"/logout.htm");
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
